import { getEditClassMenuList } from '@/services/shop/api';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-table';
import { Button, FormInstance, Upload } from 'antd';
// @ts-ignore
import Cookies from 'js-cookie';
import React, { useEffect, useRef, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

const OptForm: React.FC<any> = (props) => {
  const {
    handleModalVisible,
    handleAdd
  } = props;
  const [list, setList] = useState<any[]>([]);
  const actionRef = useRef<ActionType>();
  const [addParentClass, setAddParentClass] = useState<boolean>(false);
  const [addSubClass, setAddSubClass] = useState<boolean>(false);

  const editFormRef = useRef<FormInstance>();
  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [editModalTitle, setEditModalTitle] = useState<string>('');
  const [editPreClass, setEditPreClass] = useState<boolean>(true);
  const [editPreClassId, setEditPreClassId] = useState<string | null>(null);

  const columns: ProColumns<any>[] = [
    {
      title: '分类编号',
      dataIndex: 'rowNum',
      width: '20%',
      editable: false,
      hideInForm: true,
      hideInSearch: true
    },
    {
      title: '分类编号',
      dataIndex: 'class_id',
      width: '20%',
      editable: false,
      hideInTable: true
    },
    {
      title: '一级分类',
      dataIndex: 'class_name',
      editable: () => {
        return addParentClass
      },
      formItemProps: {
        rules: [{ required: true, message: "名称为必填项" }]
      }
    },
    {
      title: '二级分类',
      dataIndex: 'class_sub_name',
      editable: () => {
        return addSubClass
      },
      formItemProps: {
        rules: [{ required: true, message: "名称为必填项" }]
      }
    },
    {
      title: '分类描述',
      dataIndex: 'class_desc'
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: (dom, record, index, action) => [
        // 没有父类，可添加子类
        !record.pre_class_id ?
          <a key="add-sub" onClick={() => {
            if ((action as any)?.editableKeys.length == 0) {
              let idx = list.findIndex(i => i.class_id === record.class_id);
              if (idx != -1) {
                // setAddParentClass(false);
                // setAddSubClass(true);
                // const id = uuidv4().replaceAll('-', '');
                // list.splice(idx + 1, 0, {
                //   id: id,
                //   _add: true,
                //   class_rank: '2',
                //   class_id: id,
                //   pre_class_id: record.class_id
                // });
                // action?.startEditable(id);
                // const tmp = [...list];
                // setRowNum(tmp);
                // setList(tmp);
                setEditPreClass(false);
                setEditPreClassId(record.class_id);
                setEditModalTitle(`【${record.class_name}】的子分类`);
                editFormRef.current?.setFieldsValue({ class_name: record.class_name });
                setEditVisible(true);
              }
            }
          }}>
            新增子类
          </a> : null,

        <a key="delete" onClick={() => {
          setList(list.filter(item => item.id !== record.id && item.pre_class_id !== record.id));
        }}>
          删除
        </a>,

        <a key="edit" onClick={() => {
          // 编辑父类
          if (record.class_rank === '1') {
            setAddParentClass(true);
            setAddSubClass(false);
          } else {
            setAddSubClass(true);
            setAddParentClass(false);
          }
          action?.startEditable(record.id);
        }}>
          修改
        </a>,

        record.first === true ? null :
          <a key="up" onClick={() => {
            if (record.class_rank === '1') {
              const preList = list.filter(i => i.class_rank === '1');
              const tmpIdx = preList.findIndex(i => i.class_id === record.class_id);
              if (tmpIdx == 0) {
                return; // 已经是最上
              }
              const prevClass = preList[tmpIdx - 1];
              const prevIdx = list.findIndex(i => i.class_id === prevClass.class_id);
              const currIdx = list.findIndex(i => i.class_id === record.class_id);
              const subClassList = list.filter(i => i.class_rank === '2' && i.pre_class_id === record.class_id);
              list.splice(currIdx, subClassList.length + 1); // 删除
              list.splice(prevIdx, 0, ...[record, ...subClassList]); // 插入
            } else {
              const classList = list.filter(i => i.class_rank === '2' && i.pre_class_id === record.pre_class_id);
              const currIdx = classList.findIndex(i => i.class_id === record.class_id);
              if (currIdx === 0) {
                return; // 已经子分类里最上的
              }
              const prevClass = classList[currIdx - 1];
              const idx = list.findIndex(i => i.class_id === prevClass.class_id);
              list.splice(idx, 2, record, prevClass);
            }
            const tmp = [...list];
            setRowNum(tmp);
            setList(tmp);
          }}>
            上移
          </a>,

        record.last === true ? null :
          <a key="down" onClick={() => {
            if (record.class_rank === '1') {
              const preList = list.filter(i => i.class_rank === '1');
              const tmpIdx = preList.findIndex(i => i.class_id === record.class_id);
              if (tmpIdx == preList.length - 1) {
                return; // 已经是最下
              }
              const nextClass = preList[tmpIdx + 1];
              const nextIdx = list.findIndex(i => i.class_id === nextClass.class_id) + list.filter(i => i.pre_class_id === nextClass.class_id).length;
              const currIdx = list.findIndex(i => i.class_id === record.class_id);
              const subClassList = list.filter(i => i.class_rank === '2' && i.pre_class_id === record.class_id);
              list.splice(nextIdx + 1, 0, ...[record, ...subClassList]); // 插入
              list.splice(currIdx, subClassList.length + 1); // 删除
            } else {
              const classList = list.filter(i => i.class_rank === '2' && i.pre_class_id === record.pre_class_id);
              const currIdx = classList.findIndex(i => i.class_id === record.class_id);
              if (currIdx === classList.length - 1) {
                return; // 已经子分类里最下的
              }
              const nextClass = classList[currIdx + 1];
              const idx = list.findIndex(i => i.class_id === record.class_id);
              list.splice(idx, 2, nextClass, record);
            }
            const tmp = [...list];
            setRowNum(tmp);
            setList(tmp);
          }}>
            下移
          </a>
      ]
    }
  ];

  const setRowNum = (dataList: any[]) => {
    let i: number = 0, j: number = 0;
    dataList.forEach((item, idx) => {
      delete item['first'];
      delete item['last'];
      if (item.class_rank === '1') {
        if (i === 0)
          item['first'] = true;
        item['rowNum'] = (++i + '').padStart(3, '0');
        const tmp = dataList.filter(n => n.class_rank === '1');
        const nIdx = tmp.findIndex(n => n.class_id === item.class_id);
        if (nIdx === tmp.length - 1)
          item['last'] = true;
        j = 0;
      } else {
        if (j === 0)
          item['first'] = true;
        item['rowNum'] = (i + '').padStart(3, '0') + '.' + (++j + '').padStart(3, '0');
        if (dataList[idx + 1]?.pre_class_id !== item.pre_class_id)
          item['last'] = true;
      }
    });
  };

  const sort = (a: any, b: any) => a.sort - b.sort;

  useEffect(() => {
    getEditClassMenuList().then(data => {
      const classMenuList: any[] = [];
      data.filter((i: any) => i.class_rank === '1').sort(sort).forEach((item: any) => {
        classMenuList.push({ ...item, id: item.class_id });
        data.filter((j: any) => j.class_rank === '2' && j.pre_class_id === item.class_id).sort(sort).forEach((subItem: any) => {
          classMenuList.push({ ...subItem, class_sub_name: subItem.class_name, class_name: null, id: subItem.class_id });
        });
      });
      setRowNum(classMenuList);
      setList(classMenuList);
    })
  }, []);

  return <><ModalForm
    className="modal-form"
    width="90%"
    title="编辑分类"
    visible
    modalProps={{
      maskClosable: false
    }}
    onVisibleChange={handleModalVisible}
    onFinish={async (value) => {
      const class_list: any[] = [];
      list.forEach(item => {
        class_list.push({
          class_id: item.class_id,
          class_name: item.class_name || item.class_sub_name,
          class_rank: !item.pre_class_id ? 1 : 2,
          pre_class_id: item.pre_class_id,
          class_desc: item.class_desc
        })
      });
      const success = await handleAdd({
        class_list
      });
      if (success) {
        handleModalVisible(false);
      }
    }}
    submitter={{
      searchConfig: {
        resetText: '取消',
        submitText: '确定'
      }
    }}>

    <EditableProTable<any>
      rowKey="id"
      bordered
      actionRef={actionRef}
      columns={columns}
      value={list}
      rowClassName={(record, idx) => (record._add ? "newLine" : "")}
      recordCreatorProps={false}
      className='category-type-table'
      editable={{
        onCancel: async (key, record, row) => {
          actionRef.current?.cancelEditable(key);
          (actionRef.current as any).editableKeys = [];
          // if (row._add === true) {
          //   setList(list.filter(i => i.id !== key));
          // }
        },
        onSave: async (key, row, oRow, newLine) => {
          const idx = list.findIndex(i => i.id === row.id);
          if (idx == -1)
            return;
          list.splice(idx, 1);
          if (row.class_rank === '1') {
            list.push(row);
          } else {
            const preList = list.filter(i => i.class_rank === '1');
            const idx2 = preList.findIndex(i => i.class_id === row.pre_class_id);
            const nextPreId = preList[idx2 + 1]?.class_id;
            const idx3 = list.findIndex(i => i.class_id === nextPreId);
            if (idx3 == -1) {
              list.push(row);
            } else {
              list.splice(idx3, 0, row);
            }
          }
          const tmp = [...list];
          setRowNum(tmp);
          setList(tmp);
        },
        actionRender: (row, config, dom) => [dom.save, dom.cancel]
      }}
      toolbar={
        {
          menu: {
            type: 'inline',
            items: [
              {
                key: 'import',
                label: <Upload
                  action=""
                  accept="*"
                  headers={{
                    'Oper-Token': localStorage.getItem('Oper-Token')
                  }}>
                  <Button type="primary">导入分类</Button>
                </Upload>
              },
              {
                key: 'add',
                label: <Button type="primary" onClick={() => {
                  if ((actionRef.current as any)?.editableKeys.length == 0) {
                    // setAddParentClass(true);
                    // setAddSubClass(false);
                    // const id = uuidv4().replaceAll('-', '');
                    // list.splice(0, 0, {
                    //   id: id,
                    //   class_id: id,
                    //   class_rank: '1',
                    //   _add: true
                    // });
                    // actionRef.current?.startEditable(id);
                    // const tmp = [...list];
                    // setRowNum(tmp);
                    // setList(tmp);
                    setEditPreClass(true);
                    setEditPreClassId(null);
                    setEditModalTitle('一级分类');
                    setEditVisible(true);
                  }
                }}>新增一级分类</Button>
              }
            ]
          }
        }
      }
    />
    < div className="modal-tips" >
      <ExclamationCircleOutlined />
      <span>编辑商品分类信息后，请点击下方<strong>确定</strong>按钮保存结果，导入分类会覆盖当前已存在的分类信息，请谨慎操作。</span>
    </div >
  </ModalForm>
    <ModalForm formRef={editFormRef} visible={editVisible} title={`新增${editModalTitle}`} className="sub-modal-form"
      onVisibleChange={setEditVisible}
      modalProps={{ onCancel: e => editFormRef.current?.resetFields() }}
      onFinish={async formData => {
        if(editPreClass){
          delete formData['class_sub_name'];
        }else{
          delete formData['class_name'];
        }
        const id = uuidv4().replaceAll('-', '');
        const val = {
          ...formData,
          id: id,
          class_id: id,
          class_rank: editPreClass ? '1' : '2',
          _add: true
        };
        const tmp = [...list];
        if (!editPreClass && editPreClassId != null) {
          val['pre_class_id'] = editPreClassId;
          const preList = tmp.filter(i => i.class_rank === '1');
          const idx2 = preList.findIndex(i => i.class_id === editPreClassId);
          const nextPreId = preList[idx2 + 1]?.class_id;
          const idx3 = tmp.findIndex(i => i.class_id === nextPreId);
          if (idx3 == -1) {
            tmp.push(val);
          } else {
            tmp.splice(idx3, 0, val);
          }
        } else {
          tmp.push(val);
        }
        setRowNum(tmp);
        setList(tmp);
        setEditVisible(false);
        editFormRef.current?.resetFields();
      }}>
      <div>
        <table>
          <thead>
            <tr>
              <td>一级分类</td>
              <td>二级分类</td>
              <td>分类描述</td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>
                <ProFormText name="class_name" readonly={!editPreClass}
                  rules={[{ required: editPreClass, message: "名称为必填项" }]} placeholder="一级分类" />
              </td>
              <td>
                <ProFormText name="class_sub_name" readonly={editPreClass}
                  rules={[{ required: !editPreClass, message: "名称为必填项" }]} placeholder="二级分类" />
              </td>
              <td><ProFormText name="class_desc" placeholder="分类描述" /></td>
            </tr>
          </tbody>
        </table>
      </div>
    </ModalForm>
  </>
}
export default OptForm;
